package jp.eisbahn.mgapi.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import jp.eisbahn.mgapi.util.IOUtils;

public class BasicHttpFetcher implements HttpFetcher {

    @Override
    public HttpResponse fetch(HttpRequest request) throws IOException {
        OutputStreamWriter out = null;
        InputStreamReader in = null;
        try {
            String requestBody = "";
            if (request.isDoOuput()) {
                Map<String, Object> parameterMap = request.getParameterMap();
                ContentType contentType = request.getContentType();
                if (contentType.equals(ContentType.X_WWW_FORM_URLENCODED)) {
                    requestBody = createFormParameterString(parameterMap);
                } else if (contentType.equals(ContentType.JSON)) {
                    throw new UnsupportedOperationException();
                } else {
                    throw new IllegalArgumentException("Invalid contentType value. " + contentType);
                }
            }
            String urlString = request.getUrl();
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod(request.getMethod().toString());
            Map<String, String> headerMap = request.getHeaderMap();
            if (headerMap != null) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            conn.setDoOutput(request.isDoOuput());
            conn.connect();
            if (request.isDoOuput()) {
                out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
                out.write(requestBody);
                out.flush();
            }
            int responseCode = conn.getResponseCode();
            String responseMessage = conn.getResponseMessage();
            String responseBody = "";
            if (responseCode == HttpServletResponse.SC_OK
                    || responseCode == HttpServletResponse.SC_CREATED) {
                in = new InputStreamReader(conn.getInputStream(), "UTF-8");
            } else {
                InputStream errorStream = conn.getErrorStream();
                if (errorStream != null) {
                    in = new InputStreamReader(conn.getErrorStream(), "UTF-8");
                }
            }
            if (in != null) {
                BufferedReader br = new BufferedReader(in);
                String line;
                boolean first = true;
                while ((line = br.readLine()) != null) {
                    if (first) {
                        first = false;
                    } else {
                        responseBody += "\n";
                    }
                    responseBody += line;
                }
            }
            Map<String, List<String>> responseHeaderMap = conn.getHeaderFields();
            HttpResponse httpResponse = new HttpResponse(
                    responseCode, responseMessage, responseBody, responseHeaderMap);
            return httpResponse;
        } catch(MalformedURLException e) {
            throw new IllegalStateException(e);
        } catch(ProtocolException e) {
            throw new IllegalStateException(e);
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(in);
        }
    }
    
    private String createFormParameterString(Map<String, Object> parameterMap) {
        try {
            StringBuilder sb = new StringBuilder();
            Set<Entry<String,Object>> entrySet = parameterMap.entrySet();
            boolean first = true;
            for (Entry<String, Object> entry : entrySet) {
                if (first) {
                    first = false;
                } else {
                    sb.append("&");
                }
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
            }
            return sb.toString();
        } catch(UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }

}
